<?php
header ( 'Content-type:text/html;charset=utf-8' );
include_once $_SERVER ['DOCUMENT_ROOT'] . '/upacp_demo_b2b/sdk/acp_service.php';

class b2c_ctl_admin_b2bpayquery extends desktop_controller{
	public function __construct($app)
	{
		parent::__construct($app);
		header("cache-control: no-store, no-cache, must-revalidate");
	}
	
	public function index($order_id){
		//$value=$this->app->model('orders')->dump($order_id,'*','default');	
		$model=$this->app->model('orders');
		//edit by peter 2017-07-13 只查询成功的付款单
		$sql1="select a.order_id,c.payment_id,c.t_begin,(select d.`value` from sdb_base_setting d where d.`key`='ectools_payment_plugin_unionpayb2b' LIMIT 1 ) as merinfo from sdb_b2c_orders a left outer join sdb_ectools_order_bills b on a.order_id=b.rel_id left outer join sdb_ectools_payments c on b.bill_id=c.payment_id where a.order_id='".$order_id."' and c.`status`='succ'";
		$value=$model->db->select($sql1);	
		//经验证,这样反序列化无效
		//$merinfo=unserialize($value['merinfo']);
		$strPaymnet = app::get('ectools')->getConf('ectools_payment_plugin_unionpayb2b');
		$merinfo = unserialize($strPaymnet);
		$params = array(
			'version' => com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->version,
			'encoding' => 'utf-8',
			'signMethod' => com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->signMethod,
			//00查询交易
			'txnType' => '00',
			'txnSubType' => '00',
			//原始代码默认000000,b2b是000202
			'bizType' => '000202',
			//0普通商户直连
			'accessType' => '0',
			//07互联网
			'channelType' => '07',
			//商户订单号,取payment_id
			'orderId' => $value[0]['payment_id'],
			//商户号
			'merId' => $merinfo['setting']['mer_id'],
			//payment中的t_begin
			'txnTime' => date('YmdHis',$value[0]['t_begin']),	
		);

		com\unionpay\acp\sdk\AcpService::sign ( $params ); 
		$url = com\unionpay\acp\sdk\SDKConfig::getSDKConfig()->singleQueryUrl;
		$result_arr = com\unionpay\acp\sdk\AcpService::post ( $params, $url);
		//没收到200应答的情况	
		if(count($result_arr)<=0) { 
			echo '查询交易失败,请稍后再试.';
			return;
		}
		if (!com\unionpay\acp\sdk\AcpService::validate ($result_arr) ){
			echo "应答报文验签失败,请稍后再试.";
			return;
		}

		if ($result_arr["respCode"] == "00"){
			if ($result_arr["origRespCode"] == "00"){
				echo "交易成功。<br>";
			} else if ($result_arr["origRespCode"] == "03"
				|| $result_arr["origRespCode"] == "04"
				|| $result_arr["origRespCode"] == "05"){
				echo "交易处理中，请稍后查询。<br>";
			} else {
			//其他应答码做以失败处理
				echo "交易失败：" . $result_arr["origRespMsg"] . "。<br>\n";
			}
		} else if ($result_arr["respCode"] == "03"
			|| $result_arr["respCode"] == "04"
			|| $result_arr["respCode"] == "05" ){
			//后续需发起交易状态查询交易确定交易状态
			echo "处理超时，请稍后查询。<br>";
		} else {
			//其他应答码做以失败处理
			echo "失败：" . $result_arr["respMsg"] . "。<br>";
		}
	}
}
